package com.kmt.plaza.sevice.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kmt.plaza.dao.ClassifyMapper;
import com.kmt.plaza.entity.ProductImg;
import com.kmt.plaza.sevice.ClassifyService;
import com.kmt.plaza.vo.ClassifyVO;
import com.kmt.plaza.vo.ResStatus;
import com.kmt.plaza.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ClassifyServiceImpl implements ClassifyService {
    @Autowired
    private ClassifyMapper classifyMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper = new ObjectMapper();
    private Logger logger = LoggerFactory.getLogger(ClassifyServiceImpl.class);
    //查询分类列表（包含三个级别的分类）
    @Override
    public ResultVO listClassify() {
        logger.info("开始查询商品分类列表......");
        List<ClassifyVO> classifyVOS = null;
        try{
            logger.info("开始查询在redis查询商品分类列表信息......");
            //查询redis
            String classifies = stringRedisTemplate.boundValueOps("classifies").get();
            if(classifies != null){
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, ClassifyVO.class);
                classifyVOS = objectMapper.readValue(classifies, javaType);
            }else {
                //如果redis没有数据，则查询数据库
                logger.info("redis没有数据查询数据库开始......");
                classifyVOS = classifyMapper.selectAllClassify();
                String classiftStr = objectMapper.writeValueAsString(classifyVOS);
                stringRedisTemplate.boundValueOps("classifies").set(classiftStr,1, TimeUnit.DAYS);
            }
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", classifyVOS);
        return resultVO;
    }

    //查询所有一级分类，查询前六销量最高
    @Override
    public ResultVO listFirstLevelClassifies() {
        List<ClassifyVO> classifyVOS = classifyMapper.selectFirstLevelClassifies();
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", classifyVOS);
        return resultVO;
    }
}
